﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
using LeHouse.Server.Dto;
using LeHouse.Server.Service;
using System.Text;
using LeHouse.Server.WebApi.Common;
using System.IO;
namespace LeHouse.Server.WebApi.Controllers
{
    public class PersonalController : ApiController
    {
        Collateral_PersonalService bll = new Collateral_PersonalService();
        /// <summary>
        /// 资产登记的数据添加And修改
        /// </summary>
        /// <param name="s">ajax传过来的需要添加的数据</param>
        /// <returns></returns>       
        [HttpPost]
        [Route("api/Personal/PersonalOrBorrower")]
        public bool InsertOrUpdate([FromBody]PersonalOrBorrower parms)
        {
            parms.Collateral_Personal.T_State = Convert.ToInt32(EnumSelectState.waitProspect);
            parms.Collateral_Personal.T_Date = DateTime.Now;
            //如果项目号为空，是添加，获取新报告号
            if (string.IsNullOrEmpty(parms.Collateral_Personal.T_ReportNumber))
            {
                //获取New项目号
                string ReportNumber = bll.SortReportNumber();
                parms.Collateral_Personal.T_ReportNumber = ReportNumber;
                foreach (Collateral_Borrower cb in parms.Collateral_BorrowerList)
                {
                    cb.T_ReportNumber = ReportNumber;
                }
                parms.State = 1;
            }
            else
            {//否则修改

                Collateral_Personal cp = bll.Select(t => t.T_ReportNumber == parms.Collateral_Personal.T_ReportNumber).FirstOrDefault();
                if (cp == null)
                    return false;
                string ReportNumber = cp.T_ReportNumber;
                parms.Collateral_Personal.T_ReportNumber = ReportNumber;
                foreach (Collateral_Borrower cb in parms.Collateral_BorrowerList)
                {
                    cb.T_ReportNumber = ReportNumber;
                }
                parms.State = 2;
            }

            ////押物评估登记基本信息表添加and修改操作
            if (bll.PersonalOrBorrowerInsertOrUpdate(parms) == true)
            {
                return true;
            }
            else
            {
                return false;
            }
        }
        /// <summary>
        ///  资产登记的修改的显示
        /// </summary>
        /// <param name="T_ReportNumber">项目号</param>
        /// <returns></returns>
        [HttpPost]
        [Route("api/Personal/ShowCollateral_PersonalService")]
        public dynamic ShowCollateral_PersonalService([FromBody]string T_ReportNumber)
        {
            List<dynamic> dicEnum = new List<dynamic>();
            Collateral_PersonalService Perbll = new Collateral_PersonalService();
            Collateral_BorrowerService Borbll = new Collateral_BorrowerService();
            Collateral_Personal ShowPer = Perbll.Select(p => p.T_ReportNumber == T_ReportNumber).FirstOrDefault();
            List<Collateral_Borrower> ShowBor = Borbll.Select(p => p.T_ReportNumber == T_ReportNumber);
            dicEnum.Add(ShowPer);
            dicEnum.Add(ShowBor);
            return dicEnum;
        }
        /// <summary>
        /// 勘查信息的回填
        /// </summary>
        /// <param name="ReportNumber">项目号</param>
        /// <returns></returns>       
        [HttpGet]
        [Route("api/Personal/SelectProspecting")]
        public SelectProspecting SelectProspecting([FromUri]string T_ReportNumber)
        {
            SelectProspecting sps = new Dto.SelectProspecting();
            Collateral_Personal cp = bll.Select(t => t.T_ReportNumber == T_ReportNumber).FirstOrDefault();
            if (cp == null)
                sps.Message = "error";
            else
            {
                sps = bll.SelectProspecting(T_ReportNumber);
                sps.Message = "ok";
            }
            return sps;
        }

        /// <summary>
        /// 查看资产登记表的所有数据
        /// </summary>
        /// <param name="T_ReportNumber">项目号</param>
        /// <returns></returns>
        [HttpPost]
        [Route("api/Personal/SelectPersonalAll")]
        public List<Collateral_Personal> SelectPersonalAll([FromBody]string T_ReportNumber)
        {
            Collateral_PersonalService select = new Collateral_PersonalService();
            if (string.IsNullOrEmpty(T_ReportNumber))
            {
                return select.Select().OrderByDescending(t => t.T_ReportNumber).ToList();
            }
            else
            {
                //2016-11-21 杨继平进行优化
                return select.Select(p => p.T_ReportNumber.Contains(T_ReportNumber.Trim())).OrderByDescending(t => t.T_ReportNumber).ToList();
                //var d1 = select.Select().Where(p => p.T_ReportNumber.Contains(T_ReportNumber.Trim())).ToList();
            }

        }


        [HttpPost]
        [Route("api/Personal/SelectPersonalAllPage")]
        public SelectPager<dynamic> SelectPersonalAllPage([FromBody]SelectPager<dynamic> obj)
        {
            SelectPager<dynamic> sp = new SelectPager<dynamic>();
            Collateral_PersonalService staff = new Collateral_PersonalService();
            
            if (string.IsNullOrEmpty(obj.search))
            {
                long totalSize;
                var result = (from cps in staff.SelectByPagerDesc(t => t.T_ReportNumber, obj.PageIndex, obj.PageSize, out totalSize)
                              select new
                              {
                                  cps.T_ReportNumber,
                                  cps.T_Linkman,
                                  cps.T_Phone,
                                  cps.T_Located,
                                  T_Date = cps.T_Date.ToString("yyyy-MM-dd hh:mm:ss"),
                                  cps.T_State,
                                  T_StateText = EnumHelperDic.GetEnumSelectState<EnumSelectState>(cps.T_State)
                              });
                sp.Result = result.ToList<dynamic>();
                sp.PageCount = Convert.ToInt32(Math.Ceiling((double)totalSize / obj.PageSize));
                sp.TotalSize = Convert.ToInt32(totalSize);
            }
            else
            {
                if (obj.pledge_field == "看房联系人")
                {
                    long totalSize;
                    var result = (from cps in staff.SelectByPagerDesc(p => p.T_Linkman.Contains(obj.search), p => p.T_ReportNumber, obj.PageIndex, obj.PageSize, out totalSize)
                                  select new
                                  {
                                      cps.T_ReportNumber,
                                      cps.T_Linkman,
                                      cps.T_Phone,
                                      cps.T_Located,
                                      T_Date = cps.T_Date.ToString("yyyy-MM-dd hh:mm:ss"),
                                      cps.T_State,
                                      T_StateText = EnumHelperDic.GetEnumSelectState<EnumSelectState>(cps.T_State)
                                  });
                    sp.Result = result.ToList<dynamic>();
                    sp.PageCount = Convert.ToInt32(Math.Ceiling((double)totalSize / obj.PageSize));
                    sp.TotalSize = Convert.ToInt32(totalSize);
                }
                else if (obj.pledge_field == "房屋坐落")
                {
                    long totalSize;
                    var result = (from cps in staff.SelectByPagerDesc(p => p.T_Located.Contains(obj.search), p => p.T_ReportNumber, obj.PageIndex, obj.PageSize, out totalSize)
                                  select new
                                  {
                                      cps.T_ReportNumber,
                                      cps.T_Linkman,
                                      cps.T_Phone,
                                      cps.T_Located,
                                      T_Date = cps.T_Date.ToString("yyyy-MM-dd hh:mm:ss"),
                                      cps.T_State,
                                      T_StateText = EnumHelperDic.GetEnumSelectState<EnumSelectState>(cps.T_State)
                                  });
                    sp.Result = result.ToList<dynamic>();
                    sp.PageCount = Convert.ToInt32(Math.Ceiling((double)totalSize / obj.PageSize));
                    sp.TotalSize = Convert.ToInt32(totalSize);
                }
                else
                {
                    long totalSize;
                    var result = (from cps in staff.SelectByPagerDesc(p => p.T_ReportNumber.Contains(obj.search), p => p.T_ReportNumber, obj.PageIndex, obj.PageSize, out totalSize)
                                  select new
                                  {
                                      cps.T_ReportNumber,
                                      cps.T_Linkman,
                                      cps.T_Phone,
                                      cps.T_Located,
                                      T_Date = cps.T_Date.ToString("yyyy-MM-dd hh:mm:ss"),
                                      cps.T_State,
                                      T_StateText = EnumHelperDic.GetEnumSelectState<EnumSelectState>(cps.T_State)
                                  });
                    sp.Result = result.ToList<dynamic>();
                    sp.PageCount = Convert.ToInt32(Math.Ceiling((double)totalSize / obj.PageSize));
                    sp.TotalSize = Convert.ToInt32(totalSize);
                }
            }
            return sp;
        }


        /// <summary>
        /// 通过项目号获取登记基本信息
        /// </summary>
        /// <param name="P_ReportNumber"></param>
        /// <returns></returns>
        [HttpGet]
        [Route("api/Personal/SelectPersonaByReportNumber")]
        public dynamic SelectPersonaByReportNumber([FromUri] string P_ReportNumber)
        {
            Collateral_BorrowerService BorrowerService = new Collateral_BorrowerService();
            List<dynamic> dy = new List<dynamic>();
            var GETRep = bll.SelectPersonaByReportNumber(P_ReportNumber);
            var GETBor = BorrowerService.Select(p => p.T_ReportNumber == P_ReportNumber);
            dy.Add(GETRep);
            dy.Add(GETBor);
            return dy;
        }

        //  <summary>
        //  Wap查看根据谁登陆的去看他的单子
        //  </summary>
        //   <returns></returns>
        [HttpGet]
        [Route("api/Personal/WapShow")]
        public List<Collateral_Personal> WapShow([FromUri] string S_account)
        {
            System_StaffService service = new System_StaffService();
            System_Staff Staff = new System_Staff();
            Staff = service.Select(p => p.T_Account == S_account).FirstOrDefault();
            if (Staff == null)
            {
                return new List<Collateral_Personal>();
            }
            List<Collateral_Personal> s = bll.Select(p => p.T_SiteSurveyid == Staff.T_StaffID).OrderByDescending(p => p.T_ReportNumber).ToList();
            return s;
        }
        //<summary>
        //接到WAP端传来的报告号约到
        //</summary>
        //<returns></returns>
        [HttpGet]
        [Route("api/Personal/UpdateP_ReportNumberyes")]
        public bool UpdateP_ReportNumber([FromUri] string P_ReportNumber, string P_cause)
        {
            Collateral_Personal Personal = new Collateral_Personal();
            Personal = bll.Select().Where(p => p.T_ReportNumber == P_ReportNumber).FirstOrDefault();
            Personal.T_State = 1;
            Personal.T_Cause = P_cause;
            if (bll.Update(Personal) == true)
            {
                return true;
            }
            else
            {
                return false;
            }
        }
        /// <summary>
        /// 根据报告号去查约没约到加载显示
        /// </summary>
        /// <param name="P_ReportNumber"></param>
        /// <returns></returns>
        [HttpGet]
        [Route("api/Personal/selectbyP_ReportNumberss")]
        public Collateral_Personal selectbyP_ReportNumberss(string P_ReportNumber)
        {
            return bll.selectbyP_ReportNumberss(P_ReportNumber);
        }
        //<summary>
        //接到WAP端传来的报告号没约到
        //</summary>
        //<returns></returns>
        [HttpGet]
        [Route("api/Personal/UpdateP_ReportNumberNO")]
        public bool UpdateP_ReportNumberNO([FromUri] string P_ReportNumber, string P_cause)
        {
            Collateral_Personal Personal = new Collateral_Personal();
            Personal = bll.Select().Where(p => p.T_ReportNumber == P_ReportNumber).FirstOrDefault();
            Personal.T_State = 0;
            Personal.T_Cause = P_cause;
            if (bll.Update(Personal) == true)
            {
                return true;
            }
            else
            {
                return false;
            }
        }
        /// <summary>
        /// WAP 端请求模糊查询地址
        /// </summary>
        /// <param name="P_located"></param>
        /// <returns></returns> 
        [HttpGet]
        [Route("api/Personal/searchbyP_located")]
        public List<Jointshow> searchbyP_located([FromUri] string C_project)
        {
            return bll.searchbyP_located(C_project);
        }
        /// <summary>
        /// 房产抵押基本信息-删除-未预约勘查信息之前可以删除
        /// </summary>
        /// <param name="T_ReportNumber"></param>
        /// <returns></returns>
        [HttpPost]
        [Route("api/Personal/delete")]
        public bool Personal_delete([FromBody]string T_ReportNumber)
        {
            var d1 = bll.DeletePersonalAndOwnership(T_ReportNumber);
            return d1;
        }


        /// <summary>
        /// 估价信息
        /// </summary>
        /// <param name="T_ReportNumber"></param>
        /// <returns></returns>
        [HttpPost]
        [Route("api/Personal/evaluateInfo")]
        public dynamic evaluateInfo([FromBody]byValueHelper obj)
        {
            jsonManager jm = new jsonManager();
            Collateral_PersonalService personalService = new Collateral_PersonalService();
            var d1 = personalService.Select(p => p.T_ReportNumber == obj.T_ReportNumber).FirstOrDefault();

            if (d1 == null)
            {
                jm.code = 0;
                jm.msg = "查询不到项目号！";
                return Json(jm);
            }

            if (d1.T_State > 2 && d1.T_State != 4)
            {
                jm.code = 0;
                jm.msg = "该信息已经提交过，不能更改！";
                return Json(jm);
            }

            if (d1.T_State < 2)
            {
                jm.code = 0;
                jm.msg = "该项目尚未查勘，不能提交！";
                return Json(jm);
            }

            Collateral_ownershipService ownership = new Collateral_ownershipService();
            var d2 = ownership.Select(p => p.T_ReportNumber == obj.T_ReportNumber).FirstOrDefault();
            if (d2 == null)
            {
                jm.code = 0;
                jm.msg = "请在权属信息中录入房屋所有权证书信息！";
                return Json(jm);
            }

            Collateral_RealestateService realestate = new Collateral_RealestateService();
            var d3 = realestate.Select(p => p.T_ReportNumber == obj.T_ReportNumber).FirstOrDefault();
            if (d3 == null)
            {
                jm.code = 0;
                jm.msg = "请在权属信息中录入不动产权证书信息！";
                return Json(jm);
            }

            Collateral_TaxcertificateService taxcertificate = new Collateral_TaxcertificateService();
            var d4 = taxcertificate.Select(p => p.T_ReportNumber == obj.T_ReportNumber).FirstOrDefault();
            if (d4 == null)
            {
                jm.code = 0;
                jm.msg = "请在权属信息中录入中华人民共和国税收完税证明信息！";
                return Json(jm);
            }

            Collateral_BusinessContractService businessContract = new Collateral_BusinessContractService();
            var d5 = businessContract.Select(p => p.T_ReportNumber == obj.T_ReportNumber).FirstOrDefault();
            if (d5 == null)
            {
                jm.code = 0;
                jm.msg = "请在权属信息中录入存量房屋买卖合同信息！";
                return Json(jm);
            }

            System_StaffService staffService = new System_StaffService();
            try
            {
                d1.T_ValuationPurpose = obj.T_ValuationPurpose;
                d1.T_ValuationName = Convert.ToInt32(obj.T_ValuationName);
            }
            catch
            {
                jm.code = 0;
                jm.msg = "找不到该估价师信息！";
                return Json(jm);
            }
            d1.T_State = 3;
            if (personalService.Update(d1))
            {
                jm.code = 1;
                jm.msg = "提交成功";

            }
            else
            {
                jm.code = 0;
                jm.msg = "提交失败";
            }
            return Json(jm);
        }


        /// <summary>
        /// 估价信息回填
        /// </summary>
        [HttpPost]
        [Route("api/Personal/GetEvaluateInfo")]
        public dynamic GetEvaluateInfo([FromBody]string T_ReportNumber)
        {
            jsonManager jm = new jsonManager();
            Collateral_PersonalService personalService = new Collateral_PersonalService();
            var d1 =(from cps in personalService.Select(p => p.T_ReportNumber == T_ReportNumber)
                         select new
                         {
                             cps.T_SiteSurveyid,
                             cps.T_ValuationName,
                             T_ValuationNameShow = transmitHelper.getStaffByStaffID(Convert.ToInt32(cps.T_SiteSurveyid)) == null ? "" : transmitHelper.getStaffByStaffID(Convert.ToInt32(cps.T_SiteSurveyid)).T_Name,
                             T_StartDate=Convert.ToDateTime(cps.T_StartDate).ToString("yyyy-MM-dd hh:mm:ss"),
                             T_EndDate=Convert.ToDateTime(cps.T_EndDate).ToString("yyyy-MM-dd hh:mm:ss"),
                             T_ValuationDate=Convert.ToDateTime(cps.T_ValuationDate).ToString("yyyy-MM-dd hh:mm:ss"),
                             cps.T_ValuationPrice,
                             cps.T_Builtuparea,
                             cps.T_Valueofassessment,
                             cps.T_ValuationCalculation,
                             cps.T_Survey
                         }
                         ).FirstOrDefault();
            
             

            if (d1 == null)
            {
                jm.code = 0;
                jm.msg = "查询不到项目号！";
                return Json(jm);
            }

            jm.code = 1;
            jm.msg = "估价信息回填数据获取成功！";
            jm.data = d1;

            return Json(jm);
        }



        ///<summary>
        ///WAP所有录入信息保存完毕后提交操作
        ///</summary>
        [HttpPost]
        [Route("api/Personal/UpdateT_State")]
        public bool UpdateT_State([FromBody] string P_ReportNumber)
        {
            try
            {
                Collateral_Personal cp = bll.Select(t => t.T_ReportNumber == P_ReportNumber).FirstOrDefault();
                if (cp == null)
                    return false;
                cp.T_State = Convert.ToInt32(EnumSelectState.finishProspect);
                return bll.UpdateOnly(cp, p => p.T_State, p => p.T_ReportNumber == P_ReportNumber);
            }
            catch
            {
                return false;
            }
        }




        ///<summary>
        ///WAP建筑公共部位状况保存后修改主表(开始时间,结束时间)操作
        ///</summary>   
        [HttpGet]
        [Route("api/Personal/UpdateT_StartDateAndT_EndDate")]
        public bool UpdateT_StartDateAndT_EndDate([FromUri] string P_ReportNumber)
        {
            try
            {
                Collateral_Personal cp = bll.Select(t => t.T_ReportNumber == P_ReportNumber).FirstOrDefault();
                if (cp == null)
                {
                    return false;
                }
                cp.T_StartDate = DateTime.Now;//获取系统时间
                cp.T_EndDate = DateTime.Now.AddMinutes(15);//获取系统时间再加上15分钟
                return bll.Update(cp, p => p.T_ReportNumber == P_ReportNumber);

            }
            catch
            {
                return false;
            }
        }



        /// <summary>
        ///  查询出来以后将查询的小区数据导入
        /// </summary>
        /// <param name="parms"></param>
        /// <returns></returns>
        [HttpGet]
        [Route("api/Personal/selectandupdate")]
        public bool selectandupdate([FromUri]string searchP_ReportNumber, string P_ReportNumbers)
        {
            return bll.selectandupdate(searchP_ReportNumber, P_ReportNumbers);
        }



    }
}
